#!/usr/bin/python3

import sys
import librungame.util
import librungame.game.windows
import librungame.runner


def die(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


def run():
    sysInfo = librungame.util.SysInfo()
    game = librungame.game.windows.Limbo("/opt/limbo")
    runner = librungame.runner.Wine(verbose=2)
    with librungame.RunGame(sysInfo, "limbo", game, runner).context(edit_or_run=False) as rg:
        game.apply_fullscreen_or_windowed(False)
        rg.run("main")


def edit(op, args):
    sysInfo = librungame.util.SysInfo()
    game = librungame.game.windows.Limbo("/opt/limbo")
    runner = librungame.runner.Wine(verbose=0)
    with librungame.RunGame(sysInfo, "limbo", game, runner).context(edit_or_run=True):
        if op == "list":
            profileList = game.list_backup_profiles()
            if len(profileList) > 0:
                print("Profiles:")
                for c in profileList:
                    print("    %s" % (c))
            else:
                print("No backup profile found.")
        elif op == "backup":
            game.save_backup_profile("backup")
        elif op == "restore":
            game.use_backup_profile("backup")
        elif op == "use-perfect":
            game.use_perfect_profile()
        else:
            assert False


class ArgParser:

    progName = "limbo"

    class ParseError(Exception):
        pass

    @classmethod
    def print_help(cls):
        print('%s is the main entrance of game LIMBO.' % (cls.progName))
        print('   Run the game:')
        print('       %s' % (cls.progName))
        print('   Manage profiles:')
        print('       %s -l     # List profiles' % (cls.progName))
        print('       %s -b     # Backup current profile as "backup"' % (cls.progName))
        print('       %s -r     # Use "backup" profile as current profile' % (cls.progName))
        print('       %s -p     # Use the perfect profile as current profile' % (cls.progName))
        print('')

    @staticmethod
    def parseHelp():
        if sys.argv[1] == "-h" or sys.argv[1] == "--help":
            return DynObject()
        else:
            return None

    @classmethod
    def parseList(cls):
        if sys.argv[1] != "-l":
            return None

        i = 1
        while i < len(sys.argv):
            if sys.argv[i] == "-l":
                i += 1
                continue
            break
        if i < len(sys.argv):
            raise cls.ParseError("Error: Redundant argument(s) found.")
        return DynObject()

    @classmethod
    def parseBackup(cls):
        if sys.argv[1] != "-b":
            return None

        i = 1
        while i < len(sys.argv):
            if sys.argv[i] == "-b":
                i += 1
                continue
            break
        if i < len(sys.argv):
            raise cls.ParseError("Error: Redundant argument(s) found.")
        return DynObject()

    @classmethod
    def parseRestore(cls):
        if sys.argv[1] != "-r":
            return None

        i = 1
        while i < len(sys.argv):
            if sys.argv[i] == "-r":
                i += 1
                continue
            break
        if i < len(sys.argv):
            raise cls.ParseError("Error: Redundant argument(s) found.")
        return DynObject()

    @classmethod
    def parseUsePerfectProfile(cls):
        if sys.argv[1] != "-p":
            return None

        i = 1
        while i < len(sys.argv):
            if sys.argv[i] == "-p":
                i += 1
                continue
            break
        if i < len(sys.argv):
            raise cls.ParseError("Error: Redundant argument(s) found.")
        return DynObject()


class DynObject:
    pass


if __name__ == "__main__":
    op = None
    try:
        if len(sys.argv) <= 1:
            run()
            sys.exit(0)

        args = ArgParser.parseHelp()
        if args is not None:
            ArgParser.print_help()
            sys.exit(0)

        if op is None:
            args = ArgParser.parseList()
            if args is not None:
                op = "list"
        if op is None:
            args = ArgParser.parseBackup()
            if args is not None:
                op = "backup"
        if op is None:
            args = ArgParser.parseRestore()
            if args is not None:
                op = "restore"
        if op is None:
            args = ArgParser.parseUsePerfectProfile()
            if args is not None:
                op = "use-perfect"
        if op is None:
            raise ArgParser.ParseError('Argument(s) invalid.')
        edit(op, args)
    except ArgParser.ParseError as e:
        print(str(e) + ' Use "%s -h" to see usage information.' % (ArgParser.progName), file=sys.stderr)
        sys.exit(1)
